﻿using System;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Text;

using Whoever.Framework.Enum;
using Whoever.Framework.Base;

using EditorialProyectos.Business.Entities;

namespace EditorialProyectos.DataAccess.Core
{
    public class AuditLogger
    {
        internal static AuditLog GenerateAuditLog(TypeOfCRUD typeOfCRUD, DbPropertyValues oldValues, DbPropertyValues newValues, BusinessEntity entity)
        {
            return new AuditLog
            {
                Entity = entity.GetType().Name,
                TypeOfCRUD = typeOfCRUD.ToString().Substring(0, 1),
                ChangeDateTime = DateTime.Now,
                OldState = oldValues != null ? DescribeValues(oldValues) : "",
                NewState = newValues != null ? DescribeValues(newValues) : ""
            };
        }

        private static string DescribeValues(DbPropertyValues values)
        {
            if (!values.PropertyNames.Any())
                return string.Empty;
            var sb = new StringBuilder();
            sb.Append("{");
            foreach (var prop in values.PropertyNames)
                sb.Append(string.Format("{{ {0} : '{1}' }},", prop, values[prop]));
            sb.Remove(sb.Length - 1, 1).Append("}");
            return sb.ToString();
        }
    }
}
